<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 下月工作安排计划编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"
          @selectOrg="selectOrg">
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table businessCode="FACE09" :uploadArrys.sync="form.fileInfoList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileInfoList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
     
  </base-breadcrumb>
</template>

<script>
import { addWorkScheduleList, updateWorkScheduleList,seeWorkScheduleList,getWorkScheduleList} from '@/api/technical/workArrangementPlan' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BSelect,
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { branchComName:'',creatorName:'',createTime:''}, // 表单
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        branchComId: [{ required: true, message: '请选择单位名称' }],
        nextMonth: [{ required: true, message: '请选择月份' }],
        content: [{ required: true, message: '请输入计划工作内容', trigger: 'blur' },],
      }, // 校验规则
      init: false, // 初始化控件

    }
  },
  async mounted() {
    this.$route.meta.title = ['下月工作安排计划 查看', '下月工作安排计划 编辑', '下月工作安排计划 新增'][this.editModel]
       if (this.editModel != 2) {
         await this.getDetailData()
    } else {
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
         this.form.creatorName=  this.$userInfo().name;
         this.form.fillId = this.$userInfo().id;
         this.form.createTime = this.$dateFormat(new Date(), 'D')
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'branchComId',
          rules: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:false,
          isNeedAuth:true,
          checkStrictly: false,
          disabled: this.editModel == 0,
          needTags: ["CO", "BC", "PD"],
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: false
        },
      // {
      //   type: SelectCompanyAndProject,
      //   keyName: 'branchComId',
      //   label: '单位名称',
      //   disabled: this.editModel == 0,
      //   // attrs: {
      //   //     extraParams: {
      //   //       notContainTags: ['PD']
      //   //     }
      //   //   },
      //   onSelectChange: (e) => {
      //       this.form.branchComName = e.name
      //       //this.getWorkScheduleListFn()
      //     }
      //   },
        {
          keyName: 'nextMonth',
          type: 'a-month-picker',
          label: '计划月份',
          disabled: this.editModel == 0,
            attrs: {
               valueFormat: 'YYYY-MM',
            //搜索设置默认搜索日期
            defaultValue:this.doHandleDate(),
          },
          change: (e) => {
                //this.form.nextMonth = e;
            //this.getWorkScheduleListFn()

          }
        },
          {
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'createTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
           {
          keyName: 'content',
          type: 'BaseTextarea',
          label: '计划工作内容',
          disabled: this.editModel == 0,
          span: 24,
          autoSize:{ minRows: 30, maxRows: 30 },
          attrs: {
              maxLength : 3000,
            },
        },
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val.length === 1 || val.length === 2) {
        this.form.branchComId = val[val.length - 1].orgId
        this.form.branchComName = val[val.length - 1].orgName
      } else if(val.length > 2) {
        this.form.branchComId = val[val.length - 1].orgId
        this.form.branchComName = val[val.length - 2].orgName + '-' + val[val.length - 1].orgName
      }
      this.$refs.ruleForm.clearValidate('branchComId')
    },
    //请求列表数据，查到数据，提示不能重复添加
    async getWorkScheduleListFn(form){
      var flag =false;
      let req = {pageNo: 1, pageSize: 10, query: {}};
      if(form.branchComId && form.nextMonth){
         req.query = {
           branchComId:form.branchComId,
           nextMonth:form.nextMonth
         }
         let data = await getWorkScheduleList(req);
        if(data.code==200){
            flag = data.data.length>0?true:false;
        }
      }
      return flag;
    },
    //获取当前默认年月
    doHandleDate() {
    let myDate = new Date(),
    tYear = myDate.getFullYear(),
    tMonth = myDate.getMonth(),
    m =null;
    if(tMonth==11){
      m = 1;
      tYear = tYear+1;
    }else{
        m = tMonth + 1;
    }
    if (m.toString().length == 1) {
        m = "0" + m;
    }
     this.$set(this.form, 'nextMonth', tYear +'-'+ m)
    return tYear +'-'+ m;
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        seeWorkScheduleList({ id: this.id })
          .then((res) => {
            this.loading = false
            this.form = { ...this.form, ...res.data }
            this.$nextTick(() => {
              this.form.nextMonth = res.data.nextMonth;
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
   async handleSubmit(status) {
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
     let tipFlag = await this.getWorkScheduleListFn(this.form);
     if(tipFlag){
        this.$message.warning('每月每个单位只有1条数据');
        return
     }
      this.loading = true
      this.loadingBtn[status] = true
      let form = this.$clone(this.form);
      let api = [updateWorkScheduleList,addWorkScheduleList][this.editModel - 1]
      api(form)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
